import React, { useCallback, useMemo } from 'react';
import { Slider } from 'antd';
import moment from 'moment';
import styles from './index.less';

const format_2 = 'YYYY/MM/DD';
const formatter = (val: number, type = format_2) => moment(val * 1000).format(type);

const DateRangeSlider = (props: any) => {
  const { min, max, onChange, format, value } = props;

  const formatToTimeStamp = useCallback((str: string) => {
    const result = parseInt(moment(str).startOf('day').format('X'));
    return result;
  }, []);

  const displayValue: any = useMemo(() => {
    const result = [0, 0];
    if (!value || value.length != 2) return result;
    try {
      const min = formatToTimeStamp(value[0]);
      const max = formatToTimeStamp(value[1]);
      return [min, max];
    } catch (err) {
      return result;
    }
  }, [value]);

  const handleChange = useCallback(
    (value: any) => {
      const result = format ? [formatter(value[0], format), formatter(value[1], format)] : [value[0], value[1] + 86399];
      onChange && onChange(result);
    },
    [onChange, format],
  );

  return (
    <div className={styles.SliderContent}>
      <Slider
        range
        step={86400}
        min={formatToTimeStamp(min)}
        max={formatToTimeStamp(max)}
        onChange={handleChange}
        tipFormatter={formatter}
        value={displayValue}
      />
    </div>
  );
};

export default DateRangeSlider;
